﻿using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Business.BTB_StaffUsers;
using Coldairarrow.Entity.UserDTO;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers
{
    [Route("/[controller]/[action]")]
    public class TokenController : Controller
    {
        readonly IHomeBusiness _homeBus;
        readonly ILogger<TokenController> _logger;
        readonly IBTB_StaffUserBusiness _bTB_StaffUserBus;
        public TokenController( IHomeBusiness homeBus, IBTB_StaffUserBusiness bTB_StaffUserBusiness, ILogger<TokenController> logger)
        {
            _homeBus = homeBus;
            _logger = logger;
            _bTB_StaffUserBus = bTB_StaffUserBusiness;
        }

        [HttpGet]
        public async Task<object> Valid()
        {
            WeChatRequestModel model = new WeChatRequestModel();
            model.signature = Request.Query["signature"];
            model.timestamp = Request.Query["timestamp"];
            model.nonce = Request.Query["nonce"];
            model.echostr = Request.Query["echostr"];

            _logger.LogInformation("signature={0}", model.signature);
            _logger.LogInformation("timestamp={0}", model.timestamp);
            _logger.LogInformation("nonce={0}", model.nonce);
            _logger.LogInformation("echostr={0}", model.echostr);

            string code = Request.Query["code"];
            string state = Request.Query["state"];

            string data = "";
            if (model.signature != null && model.signature.Length > 0)
            {
                data = _homeBus.GetTheToken(model);
                return data;
            }
            else if (code != null && code.Length > 0)
            {
                User input = new User();
                input.Codes = code;

                //data = "openid=123456&asd=0987";
                data = await _bTB_StaffUserBus.SaveGZHData(input);
                string url = "";
                if (!state.IsNullOrEmpty() && state.Trim().ToLower().Equals("lysc00"))
                {
                    if (!data.IsNullOrEmpty())
                    {
                        OpenIdInputDTO supt = new OpenIdInputDTO();
                        supt.OpenId = GetParams("openid",data);
                        var token = await _bTB_StaffUserBus.OpenIdsLogin(supt);

                        if (!token.IsNullOrEmpty())
                        {
                            url = ConfigurationUtil.GetSection("Indentity:bsjurl");
                            url = url + "?" + data + "&state=1&token=" + token+ "&sceneType=0";
                        }
                        else
                        {
                            url = ConfigurationUtil.GetSection("Indentity:bsjurl");
                            url = url + "?" + data + "&state=0&token=null&sceneType=0";
                        }
                    }
                    else
                    {
                        url = ConfigurationUtil.GetSection("Indentity:loginurl");
                        url = url + "?openid=null&state=-1&token=null&sceneType=0";
                    }
                }
                else if (!state.IsNullOrEmpty() && state.Trim().ToLower().Equals("lysc01"))
                {
                    url = ConfigurationUtil.GetSection("Indentity:bsjurl");
                    if (!data.IsNullOrEmpty())
                    {
                        url = url + "?" + data + "&state=1&sceneType=1";
                    }
                    else 
                    {
                        url = url + "?openid=null&state=-1&sceneType=0";
                    }
                }
                else
                {
                    url = ConfigurationUtil.GetSection("Indentity:indexurl");
                }
                
                Response.Redirect(url);
            }

            return data;
        }


        public static string GetParams(string paramName,string url)
        {
            var signedUrl = Regex.Match(url, paramName + "=([^&]*)");
            return signedUrl.Groups[1].ToString();
        }
    }
}
